<?php
/*
 module:		会员充值订单
 create_time:	2022-04-05 20:59:05
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\ZhTopCard;
use app\api\service\ZhBalanceService;
use app\api\service\ZhVipOrderService;
use app\api\model\ZhVipOrder as ZhVipOrderModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\api\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\VipSys as VipSysModel;
use app\api\model\ZhPayLog as ZhPayLogModel;
use app\api\service\PaymentService;
use app\api\model\ZhTopCard as ZhTopCardModel;

class ZhVipOrder extends Common
{


    /**
     * @api             {get} /ZhVipOrder/index 01、首页数据列表
     * @apiGroup        ZhVipOrder
     * @apiVersion      1.0.0
     * @apiDescription  首页数据列表
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (输入参数：) {int}            [limit] 每页数据条数（默认20）
     * @apiParam (输入参数：) {int}            [page] 当前页码
     * @apiParam (输入参数：) {string}        [order_sn] 订单号
     * @apiParam (输入参数：) {int}            [status] 订单状态 已支付|1|success,待支付|0|danger,已取消|2|info
     * @apiParam (输入参数：) {string}        [vip_name] 会员名称
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据
     * @apiParam (成功返回参数：) {string}        array.data.list 返回数据列表
     * @apiParam (成功返回参数：) {string}        array.data.count 返回数据总数
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"查询失败"}
     */
    function index()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->uid;
        $type     = $this->request->get('type',1);//1会员  2置顶卡
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');

        $where             = [];
        $where['wxapp_id'] = $wxapp_id;
        $where['u_id']     = $uId;
        $where['status']   = 1;
        $where['type']   = $type;

        $field   = '*';
        $orderby = 'id desc';

        $res = ZhVipOrderService::indexList(formatWhere($where), $field, $orderby, $limit, $page);
        foreach ($res['list'] as &$v) {
            $tip = $v['type'] == 1 ? '天会员' : '置顶卡';
            $v['title']      = '成功充值' . $v['vip_days'] .$tip;
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
        }
        unset($v);
        return $this->ajaxReturn($this->successCode, '返回成功', htmlOutList($res));
    }

    /**
     * @api             {get} /ZhVipOrder/view 02、查看详情
     * @apiGroup        ZhVipOrder
     * @apiVersion      1.0.0
     * @apiDescription  查看详情
     * @apiParam (输入参数：) {string}            id 主键ID
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function view()
    {
        $data['id'] = $this->request->get('id', '', 'serach_in');
        $field      = 'id,wxapp_id,order_sn,status,u_id,vip_id,vip_name,vip_price,vip_days,vip_end_days,createtime';
        $res        = checkData(ZhVipOrderModel::field($field)->where($data)->find());
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    /**
     * @api             {post} /ZhVipOrder/add 03、添加
     * @apiGroup        ZhVipOrder
     * @apiVersion      1.0.0
     * @apiDescription  添加
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (输入参数：) {string}            wxapp_id 平台id
     * @apiParam (输入参数：) {string}            order_sn 订单号
     * @apiParam (输入参数：) {int}                status 订单状态 已支付|1|success,待支付|0|danger,已取消|2|info
     * @apiParam (输入参数：) {int}                u_id 用户id
     * @apiParam (输入参数：) {int}                vip_id 会员id
     * @apiParam (输入参数：) {string}            vip_name 会员名称
     * @apiParam (输入参数：) {string}            vip_price 会员价格
     * @apiParam (输入参数：) {string}            vip_days 会员有效时长
     * @apiParam (输入参数：) {string}            vip_end_days 会员到期时间
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码  201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.msg 返回成功消息
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":"操作成功"}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"操作失败"}
     */
    function add()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->post('uid');
        $op  = $this->request->post('op');
        if($op=="test"){
            $uId=774;
        }
        $id       = $this->request->post('id', '', 'serach_in');// 会员菜单id
        $type     = $this->request->post('type', 'wx', 'serach_in');
        $category = $this->request->post('category', 1, 'serach_in');//1会员充值  2置顶卡
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if(!in_array($category,[1,2])){
            return $this->ajaxReturn($this->errorCode, '订单类型错误');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        if (!$id) {
            return $this->ajaxReturn($this->errorCode, '缺少信息参数');
        }
        if($category==1){
            $VipSysData = VipSysModel::where(['wxapp_id' => $wxapp_id, 'id' => $id])->find();
            if ($user['expires_time'] && $user['expires_time'] > time()) {
                $expiresTime = $user['expires_time'];
            } else {
                $expiresTime = strtotime(date('Y-m-d', time() + 86400));
            }

        }else{
            $VipSysData = ZhTopCardModel::where(['id' => $id])->find();
            if ($user['top_card_expiry'] && $user['top_card_expiry'] > time()) {
                $expiresTime = $user['top_card_expiry'];
            } else {
                $expiresTime = time();
            }
            if($VipSysData){
                $VipSysData['vip_name'] = $VipSysData['name'];
                $VipSysData['days'] = $VipSysData['day'];
            }
        }
        if (!$VipSysData) {
            return $this->ajaxReturn($this->errorCode, '信息参数错误');
        }
        $zhVipOrderId = ZhVipOrderModel::insertGetId([
            'wxapp_id'         => $wxapp_id,
            'order_sn'         => $uId . '0' . $wxapp_id . time() . rand(100, 999),
            'status'           => 0,
            'u_id'             => $uId,
            'vip_id'           => $VipSysData['id'],
            'vip_name'         => $VipSysData['vip_name'],
            'vip_price'        => $VipSysData['price'],
            'vip_days'         => $VipSysData['days'],
            'vip_end_days'     => $expiresTime + 86400 * $VipSysData['days'],
            'vip_exchange_num' => $VipSysData['exchange_num']??0,
            'createtime'       => time(),
            'type'             => $category
        ]);
        if ($zhVipOrderId) {
            $zhVipOrderData = ZhVipOrderModel::where(['id' => $zhVipOrderId, 'wxapp_id' => $wxapp_id])->find();
            if ($zhVipOrderData) {
                $res = ZhPayLogModel::insert([
                    'wxapp_id'         => $wxapp_id,
                    'uid'              => $uId,
                    'order_sn'         => $zhVipOrderData['order_sn'],
                    'price'            => $zhVipOrderData['vip_price'],
                    'status'           => 0,
                    'type'             => $zhVipOrderData['type']==1?'充值会员':'购买置顶卡',
                    'vip_id'           => $zhVipOrderData['vip_id'],
                    'vip_name'         => $zhVipOrderData['vip_name'],
                    'vip_price'        => $zhVipOrderData['vip_price'],
                    'vip_days'         => $zhVipOrderData['vip_days'],
                    'vip_end_days'     => $zhVipOrderData['vip_end_days'],
                    'vip_exchange_num' => $VipSysData['exchange_num']??0,
                    'create_time'      => date('Y-m-d H:i:s', time())
                ]);
                if ($res) {
                    try {
                        $notify_url = 'http://' . $_SERVER['HTTP_HOST'] . '/api/ZhVipOrder/payResult/wxapp_id/' . $wxapp_id;
                        if ($type == 'wx') {
                            $trade_type = 'JSAPI';
                        } elseif ($type == 'app') {
                            $trade_type = 'APP';
                        } elseif ($type == 'H5') {
                            $trade_type = 'MWEB';
                        } elseif ($type == 'H5-wx') {
                            $trade_type     = 'JSAPI';
                            $user['openid'] = $user['official_account_openid'];
                        }

                        $js_pay = PaymentService::instance($wxapp_id, $type)->create($user['openid'], $zhVipOrderData['order_sn'], $zhVipOrderData['vip_price'], $zhVipOrderData['type']==1?'充值会员':'购买置顶卡', ['notify_url' => $notify_url], $trade_type);

                        return $this->ajaxReturn($this->successCode, '操作成功  uid: '.$uId.' openid:'.$user['openid'], ['order' => $zhVipOrderData['order_sn'], 'paydata' => $js_pay]);
                    } catch (\Exception $e) {
                        trace('进入购买会员报错 uid:' . $uId." openid: ".$user['openid'], 'notify_' . date('Y_m_d'));
                        $msg=" uid:".$uId." openid: ".$user['openid']."报错： ";
                        return $this->ajaxReturn($this->errorCode,$e->getMessage());
                    }
                }
            }
        }

    }

    // 支付回调
    public function payResult()
    {
        $wxapp_id = input('wxapp_id');
        trace('进入回调' . $wxapp_id, 'notify_' . date('Y_m_d'));
        $app      = PaymentService::instance($wxapp_id)::getPayApp();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($wxapp_id) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            trace($message, 'notify_' . date('Y_m_d'));
            $order = ZhVipOrderModel::where(['order_sn' => $message['out_trade_no']])->find();
            if (!$order || $order->status == 1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {

                    // 修改礼币充值订单和充值记录状态
                    ZhVipOrderModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status' => 1]);
                    ZhPayLogModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status' => 1, 'wx_order_sn' => $message['transaction_id']]);
                    // 更新用户礼币余额
                    $ZhMemberData = MemberModel::where([
                        'uid'      => $order['u_id'],
                        'wxapp_id' => $wxapp_id
                    ])->find();

                    if($order['type']==1){//充值会员订单
                        //有会员数据
                        if ($ZhMemberData) {
                            if (!$ZhMemberData['vip_number']) {//如是果没有有会员卡号，9 + 手机号后四位
                                $vipNum = '9' . time() . substr($ZhMemberData['phone'], -4, 4);
                            } else {
                                $vipNum = $ZhMemberData['vip_number'];
                            }
                            //购买会员赠送7天置顶卡
                            if ($ZhMemberData['top_card_expiry'] && $ZhMemberData['top_card_expiry'] > time()) {
                                $expiresTime = $ZhMemberData['top_card_expiry'];
                            } else {
                                $expiresTime = time();
                            }

                            $expiresTime =  $expiresTime + 86400 * 7;

                            MemberModel::where([
                                'uid'      => $order['u_id'],
                                'wxapp_id' => $wxapp_id
                            ])->update([
                                'is_vip'       => 1,
                                'vip_number'   => $vipNum,
                                'expires_time' => $order['vip_end_days'],
                                'vip_id'=>$order['vip_id'],
                                'exchange_num' => Db::raw('exchange_num+' . $order['vip_exchange_num']),
                                'top_card_expiry'=>$expiresTime
                            ]);
                            //todo: 给上级红娘发奖励 gc_vip_site.commission_money_json 查询奖励配置
                            $this->sendMatchmakerPrize($ZhMemberData['matchmaker_id'], $wxapp_id, $order['vip_id'], $message['out_trade_no']);
                        }


                    }else{

                        MemberModel::where([
                            'uid'      => $order['u_id'],
                            'wxapp_id' => $wxapp_id
                        ])->update([
                            'top_card_expiry' => $order['vip_end_days'],
                        ]);

                    }

                    // 用户支付失败
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response->send(); // return $response;
    }

    public function test(){
        return false;
        $this->sendMatchmakerPrize(148, 3, 12, "aaaa");
        return "ok";
    }

    //发放上级红娘奖励
    private function sendMatchmakerPrize($matchmakerId, $wxappId, $vipId, $orderNo){
        if($matchmakerId > 0) {//有上级红娘
            //查找红娘信息，并获取等级
            $matchmaker = \app\api\model\ZhMatchmaker::where('matchmaker_id', $matchmakerId)->find();
            if(empty($matchmaker)) {
                return;
            }
            $matchmaker = $matchmaker->toArray();
//            print_r($matchmaker);exit;
            //查找奖励配置
            $commission_money_json = [];
            $vipSysData = VipSysModel::where(['wxapp_id' => $wxappId, 'id' => $vipId])->find();
            if (!empty($vipSysData['commission_money_json'])) {
                $tmpJson = json_decode($vipSysData['commission_money_json'], true);
                foreach ($tmpJson as $v) {
                    $commission_money_json[$v['id']] = $v['money'];
                }
            }
            //print_r($commission_money_json); exit;
            //特定等级的奖励
            if(isset($commission_money_json[$matchmaker['level_id']])){
                $money = $commission_money_json[$matchmaker['level_id']];
                //处理奖励发放的逻辑
                ZhBalanceService::updateMoneyBalanceLog($wxappId, $matchmaker['u_id'], $money, '收入', '佳人购买 '. $vipSysData['vip_name'], $orderNo);
            }
        }
    }

}

